# -*- coding: utf-8 -*-
import FPLib
import os
import json
import re
import datetime
import decimal


class Encoder(json.JSONEncoder):

    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, datetime.date):
            return obj.strftime("%Y-%m-%d")
        elif isinstance(obj, decimal.Decimal):
            return float(obj)
        else:
            return json.JSONEncoder.default(self, obj)


class JSON(object):

    def __init__(self, arg):
        super(JSON, self).__init__()

    @classmethod
    def dumps(self, data, **kwargs):
        return self.stringify(data, **kwargs)

    @classmethod
    def loads(self, str, **kwargs):
        return self.parse(str, **kwargs)

    @classmethod
    def stringify(self, data, **kwargs):
        return json.dumps(data, cls=Encoder, **kwargs)

    @classmethod
    def parse(self, str, **kwargs):
        json_str = self._format_json(str)
        try:
            return json.loads(json_str, **kwargs)
        except Exception as e:
            pass
        return None

    @classmethod
    def loadFile(self, file):
        try:
            if os.path.exists(file):
                with open(file, 'r') as f:
                    return self.parse(f.read())
        except Exception as e:
            pass
        return None

    @classmethod
    def saveFile(self, file, data):
        try:
            d = self.stringify(data)
            with open(file, 'w') as f:
                f.write(d)
        except Exception as e:
            return False
        return True

    @classmethod
    def _format_json(self, str):
        text = str.strip()
        regex = r'\s*(#|\/{2}).*$'
        regex_inline = r'(:?(?:\s)*([A-Za-z\d\.{}]*)|((?<=\").*\"),?)(?:\s)*(((#|(\/{2})).*)|)$'
        lines = text.split('\n')

        for index, line in enumerate(lines):
            if re.search(regex, line):
                if re.search(r'^' + regex, line, re.IGNORECASE):
                    lines[index] = ""
                elif re.search(regex_inline, line):
                    lines[index] = re.sub(regex_inline, r'\1', line)
        try:
            return '\n'.join(lines)
        except Exception as e:
            return ""
